//
//  SYAFNTool.swift
//  SingWeibo
//
//  Created by shiying on 15/12/18.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import AFNetworking
enum SYAFNToolError: Int {
    case emptyAccessToken = -1 //AccessToken 没有值
    case emptyUid = -2 // uid 没有值
    
    // 将错误的code描述关联起来，使用计算型属性，get方法只读
    var errorDescription: String {
        get{
            switch self {
            case SYAFNToolError.emptyAccessToken:
                return "没有值"
            case SYAFNToolError.emptyUid:
                return "没有值"
            }
        }
    }
    
    // 定义一个方法，返回一个错误
    func error() ->NSError {
        return NSError(domain: "error", code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}


class SYAFNTool: AFHTTPSessionManager {
    
    //MARK: - 单例
    static let sharedInsetace:SYAFNTool = SYAFNTool()
    
    private init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        /// 设置响应序列化器，支持text/plain
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK： - 拼接回调地址
    /// APPKEY
    @objc private let client_id = "3836231479"
    
    // App Secret：5ff14f930f94bd5b78b1413319454601
    let client_secret = "5ff14f930f94bd5b78b1413319454601"
    
    /// 回调地址
    let redirect_uri = "http://www.baidu.com/"
    
    /// 拼接回调地址
    func oAuthURL() -> NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    /*
    
    必选	类型及范围	说明
    client_id	true	string	申请应用时分配的AppKey。
    client_secret	true	string	申请应用时分配的AppSecret。
    grant_type	true	string	请求的类型，填写authorization_code
    
    grant_type为authorization_code时
    必选	类型及范围	说明
    code	true	string	调用authorize获得的code值。
    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。

    */
    
    /// 加载Access_token
    // 当请求成功或者失败都要告诉调用方，创建一个闭包
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        /// 获取授权
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        /// 获取授权参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
         /// 根据需求，POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in

            //闭包回调
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
//                print("error\(error)")
                finished(result: nil, error: error)
        }
    }
    
    //MARK: - 加载用户信息
    func loadUserInfo(finised: (reslut: [String: AnyObject]?, error: NSError?) ->()) {
        
        //判断UserAccount有没有值
        // 1.守卫
//        SYUseAccount.loadUserAccount()?.access_token = nil // 模拟access_token 有没有值
        guard let access_token = SYUseAccount.loadUserAccount()?.access_token else {
            
            //能进来就是没有值
            print("access_token 没有值")
            let error = SYAFNToolError.emptyAccessToken.error()
            finised(reslut: nil, error: error) //回调闭包
            
            return
        }
        
        // 2.用户的uid
        guard let uid =  SYUseAccount.loadUserAccount()?.uid else {
            
            //能进来就是没有值：守卫
            print("uid 没有值")
            let error = SYAFNToolError.emptyUid.error()
            finised(reslut: nil, error: error)
            
            return
        }
        
        // 3.URL地址
        let urlString = "2/users/show.json"
        // 4.请求参数
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        // 5.发送请求获取用户数据
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("result\(result)")
            // 6.调用准备好的闭包，将值传回去
            let dict = result as? [String: AnyObject]
            finised(reslut: dict, error: nil)
            
            }) { (_, error) -> Void in
                
//                print("error\(error)")
                // 6.调用准备好的闭包，将值传回去
                finised(reslut: nil, error: error)
        }
    }
    //MARK: - 加载微博数据信息
    func loadStatus(since_id: Int, max_id: Int,finished:(result: [String: AnyObject]?, error: NSError?) ->()) {
        
        // 没有值就进来
        guard let access_token = SYUseAccount.loadUserAccount()?.access_token else {
            let error = SYAFNToolError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        // 获取URL
        let urlString = "2/statuses/home_timeline.json"
        
        var parameters:[String : AnyObject] = [
            "access_token": access_token
        ]
        if since_id > 0 {
            parameters["since_id"] = since_id // 下拉刷新， ID比他大的就在前面
        } else if max_id > 0{
            
            // 因为0 那里重复了，上拉刷新的时候，多出了一个
            parameters["max_id"] = max_id - 1  // 上拉刷新
        }
        
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            let dict = result as! [String: AnyObject]
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    // MARK: - 发布微博
    func sendStatus(status: String,image: UIImage?, finished:(result: [String: AnyObject]?, error: NSError?) ->()) {
        
        guard let access_token = SYUseAccount.loadUserAccount()?.access_token else {
            let error = SYAFNToolError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = [
            "access_token" : access_token,
            "status" : status,
        ]
        
        if let img = image {
            sendPhotoStatus(parameters, status: status, image: img, fininshed: finished)
        } else {
        
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                let dict = result as? [String : AnyObject]
                
                finished(result: dict, error: nil)
                }) { (_, error) -> Void in
                    
                    finished(result: nil, error: error)
            }
        }
    }
    
    // MARK: - 发布带图片的微博
    func sendPhotoStatus(parameters: [String: AnyObject], status: String, image: UIImage, fininshed:(result: [String: AnyObject]?, error: NSError?)->()){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json" // 发布图片微博的URL
        
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            // 将图片转换成二进制数据
            let imageData = UIImagePNGRepresentation(image)!
            formData.appendPartWithFileData(imageData, name: "pic", fileName: "", mimeType: "image/png")
   
            }, success: { (_, result) -> Void in
                let dict = result as? [String : AnyObject]
                fininshed(result: dict, error: nil)
            }) { (_, error) -> Void in
                fininshed(result: nil, error: error)
        }
    }
    
    //MARK： - 评论
    func loadComments(id: Int, finished:(result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        guard let access_token = SYUseAccount.loadUserAccount()?.access_token else {
            let error = SYAFNToolError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        // 获取url
        let urlString = "https://api.weibo.com/2/comments/show.json"
        
        var parameters = [
            "access_token" : access_token,
            "id" : id
        ]
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
}
